'use strict';
const vkPay = require("vk-uni-pay");
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/pages/kh/yhsj/czjl/refund 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */

	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let {
			uid,
			out_trade_no,
			refund_desc,
			refund_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------

		if (userInfo.username != "admin") {
			res = { code: 0, msg: '操作失败！非admin账户不能操作退款' };
			return res;
		}

		// 这里不需要传pid的值，猜测可能是因为vkpay在发起支付时已记录该订单的pid值，发起退款时自动获取pid
		let refundRes = await vkPay.refund({
			out_trade_no: out_trade_no,
			refund_desc: refund_desc || "退款说明",
			refund_fee: refund_fee
		});
		if (refundRes.code !== 0) {
			return refundRes;
		}
		//修改订单状态为已退款。0：未支付  1：已支付  2：已退款
		let edit_pay_status = await db.collection('a_recharge').where({ out_trade_no: out_trade_no }).update({
			pay_status: 2,
			remark: "已退款。退款金额(单位：分)：" + refund_fee || "全额"
		})

		// 执行add命令，添加退款操作日志
		let dbName = "a_log"; // 表名
		res.id = await vk.baseDao.add({
			dbName,
			dataJson: {
				user_id: userInfo._id,
				username: userInfo.username,
				ip: originalParam.context.CLIENTIP,
				osName: originalParam.context.osName,
				osVersion: originalParam.context.osVersion,
				deviceId: originalParam.context.deviceId,
				ua: originalParam.context.ua,
				remark: "后台操作退款记录",
				_add_time,
				_add_time_str
			}
		});
		
		res = { code: 0, msg: '退款成功' };

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
